package com.tgy.JUC.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/***
 * @ClassName: CASDemo2
 * @Description:
 * @Auther: 送你一块二向箔
 * @Date: 15:06 2022/3/16
 * @version : V1.0
 */
public class CASDemo2 {
    public static void main(String[] args) {
        //这儿泛型写成 Integer 注意 -128-127
        AtomicStampedReference<String> atomic = new AtomicStampedReference<String>("2022",1);

        new Thread(()->{
            Integer stamp = atomic.getStamp();//获得版本号
            System.out.println("线程一 1=> "+stamp);
            try {
                TimeUnit.SECONDS.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(atomic.compareAndSet("2022", "1997", 1, atomic.getStamp()+1));
            System.out.println("线程一 2=> "+atomic.getStamp());
            System.out.println(atomic.compareAndSet("1997", "2022", 1, atomic.getStamp()+1));
            System.out.println("线程一 3=> "+atomic.getStamp());
        },"线程一").start();

        new Thread(()->{
            int stamp = atomic.getStamp();//获得版本号
            System.out.println("线程二 1=> "+stamp);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(atomic.compareAndSet("2022", "6666", stamp, atomic.getStamp()+1));
            System.out.println("线程二 2=> "+atomic.getStamp());
            System.out.println(atomic.compareAndSet("1997", "2022", stamp, atomic.getStamp()+1));
            System.out.println("线程二 3=> "+atomic.getStamp());
        },"线程二").start();

    }
}
